package com.minelx.datamicroscope.querylanguage.data.sql;

public class FieldBelongs {

	private final String tableAlias;

	private final String fieldName;

	private FieldBelongs(String tableAlias, String fieldName) {
		this.tableAlias = tableAlias;
		this.fieldName = fieldName;
	}

	public String tableAlias() {
		if (tableAlias == null) {
			throw new IllegalStateException("accessing table alias from a simple FieldBelongs which has no table alias.");
		}
		return tableAlias;
	}

	public String fieldName() {
		return fieldName;
	}

	public static FieldBelongs create(String tableAlias, String fieldName) {
		return new FieldBelongs(tableAlias, fieldName);
	}

	public static FieldBelongs from(String pattern) {
		return create(
				gainTableAlias(pattern),
				gainFieldName(pattern));
	}

	private static String gainTableAlias(String pattern) {
		if (!pattern.contains(".")) {
			return null; // null if pattern contains not separator
		}
		return pattern.split("\\.")[0];
	}

	private static String gainFieldName(String pattern) {
		if (!pattern.contains(".")) {
			return pattern;
		}
		return pattern.split("\\.")[1];
	}

	@Override
	public String toString() {
		return "FieldBelongs{" +
				"tableAlias='" + tableAlias + '\'' +
				", fieldName='" + fieldName + '\'' +
				'}';
	}
}
